<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ServiceCotroller extends Controller
{
    //列表
    public function lists(Request $request,$user_id){
        //查询用户
        $where_article_user[] = ['user_id','=',$user_id];
        $article_id = Db::table('article_user')->where($where_article_user)->pluck('article_id')->toArray();

    	$where[] = ['menu_article_id','=','4'];
    	$articles = Db::table('article')
                    ->where($where)
                    ->whereIn('id',$article_id)
                    ->orderBy('order','DESC')
                    ->paginate(15);

    	foreach ($articles as $key => $value) {
            if(!empty($value->image)){
                $value->image = Storage::url($value->image);
            }
        }

        //查询昵称
        $email = Db::table('users')->where('id','=',$user_id)->value('email');

    	return view('service_lists',['articles'=>$articles, 'email'=>$email, 'user_id'=>$user_id]);
    }

    //添加
    public function add_service(Request $request, $user_id){

    	return view('service_add',['user_id'=>$user_id]);
    }

    //添加报告
    public function add_service_do(Request $request){
    	$input = $request->input();
    	$input['time'] = time();
    	$input['menu_article_id'] = '4';


    	$image = !empty($request->file('image'))?$request->file('image'):[];

        if(!empty($image)){
            $path = $image->store('public/upload');
            $input['image'] = $path;
        }else{
            $path = null;
            unset($input['image']);
        }

    	if(empty($input['id'])){
            $user_id = $input['user_id'];
            unset($input['user_id']);

    		$article_id = Db::table('article')->insertGetId($input);

            $article_user_where[] = ['user_id','=',$user_id];
            $article_user_where[] = ['article_id','=',$article_id];
            $article_user = Db::table('article_user')->where($article_user_where)->first();

            if(empty($article_user)){
                $article_user_insert['article_id'] = $article_id;
                $article_user_insert['user_id'] = $user_id;


                Db::table('article_user')->insert($article_user_insert);
            }
    	}else{
    		Db::table('article')->where('id','=',$input['id'])->update($input);
    	}

    	return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }

    //编辑新闻
    public function edit_service(Request $request,$id){
    	$where[] = ['id','=',$id];
    	$articles = Db::table('article')->where($where)->first();
    	$articles->image = Storage::url($articles->image);

    	return view('service_edit',['articles'=>$articles, 'id'=>$id]);
    }
}
